package com.i2863.shiroDemo.web;

import com.i2863.shiroDemo.dto.UserInfo;
import com.i2863.shiroDemo.entity.Permission;
import com.i2863.shiroDemo.entity.Role;
import com.i2863.shiroDemo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class BaseController {

    protected UserInfo getUserInfo() {
        return (UserInfo) SecurityUtils.getSubject().getPrincipal();
    }

    protected Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    Permission getSuperPermission() {
        return (Permission) getSession().getAttribute("superPermission");
    }

    Role getSuperRole() {
        return (Role) getSession().getAttribute("superRole");
    }

    @SuppressWarnings("unchecked")
    protected List<User> getSuperUser() {
        return (List<User>) getSession().getAttribute("superUsers");
    }

    String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

}